Debugging Memory Leaks in Python
| Written: | 2025-06-24 | 
| Tags: | #python #snippet #debugging | 
I ran into a memory leak while building a program synthesis loop in Python (I know, I know...). Debugging this turns out to be a fairly pleasant experience however. The package objgraph provides all the tool needed to see which elements are dangling from where.
Here's the complete snippet:
import readline, rlcompleter, code, objgraph
print("before:")
objgraph.show_growth(limit=3)
print("\n\n")
# your code here
print("\n\nafter:")
objgraph.show_growth()
# helper to show a random graph thingy
def show_random_graph():
    refs = objgraph.find_backref_chain(
        random.choice(objgraph.by_type('MathNode')),
        objgraph.is_proper_module
    )
    objgraph.show_chain(refs)
    return refs
lvars = {**globals(), **locals()}
readline.set_completer(rlcompleter.Completer(lvars).complete)
# optional: allow global python repl history:
import os
readline.parse_and_bind("tab: complete")
readline.read_history_file(os.environ['HOME'] + '.python_history')
# this spawns the interactive console:
# here you can call show_random_graph() to see a random graph
code.InteractiveConsole(locals=lvars).interact()
readline.write_history_file(os.environ['HOME'] + '.python_history')
Make sure xdots and objgraph is installed and you're ready to go debug your thing.